<template>
  <div class="video-generation">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">🎬 AI视频生成工具</span>
          <span class="header-subtitle">基于 Sora 视频生成</span>
        </div>
      </template>

      <div class="generation-container">
        <!-- 左侧：参数设置 -->
        <div class="params-panel">
          <el-form :model="form" label-width="120px" label-position="top">
            <el-form-item label="模型选择" required>
              <el-select v-model="form.model" placeholder="请选择模型" style="width: 100%">
                <el-option label="sora-2（标准版）" value="sora-2" />
                <!-- <el-option label="sora-2-pro（专业版）" value="sora-2-pro" /> -->
              </el-select>
            </el-form-item>

            <el-form-item label="视频描述（Prompt）" required>
              <el-input
                v-model="form.prompt"
                type="textarea"
                :rows="6"
                placeholder="请详细描述你想要生成的视频内容，例如：一只可爱的橘猫在舞台上弹钢琴，周围有观众..."
                maxlength="1000"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="视频时长（秒）">
              <el-select v-model="form.seconds" placeholder="选择时长" style="width: 100%">
                <el-option label="4秒" value="4" />
                <el-option label="10秒" value="10" />
                <el-option label="15秒（默认）" value="15" />
                <el-option 
                  v-if="form.model === 'sora-2-pro'" 
                  label="25秒（仅Pro）" 
                  value="25" 
                />
              </el-select>
              <div class="tip-text">
                <el-icon><InfoFilled /></el-icon>
                10秒约1-3分钟，15秒约+2分钟，HD高清约+8分钟
              </div>
            </el-form-item>

            <el-form-item label="视频分辨率">
              <el-select v-model="form.size" placeholder="选择分辨率" style="width: 100%">
                <el-option label="720P 横屏 (1280x720)" value="1280x720" />
                <el-option label="720P 竖屏 (720x1280)" value="720x1280" />
                <el-option 
                  v-if="form.model === 'sora-2-pro'" 
                  label="1080P 横屏 (1792x1024)" 
                  value="1792x1024" 
                />
                <el-option 
                  v-if="form.model === 'sora-2-pro'" 
                  label="1080P 竖屏 (1024x1792)" 
                  value="1024x1792" 
                />
              </el-select>
            </el-form-item>

            <el-form-item label="参考图片（可选）">
              <el-upload
                class="image-uploader"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleImageChange"
                accept="image/*"
              >
                <el-button type="primary" :icon="Upload">上传参考图片</el-button>
              </el-upload>
              <div v-if="referenceImage" class="reference-image-preview">
                <img :src="referenceImageUrl" alt="参考图片" />
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  circle
                  @click="removeReferenceImage"
                />
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="generating"
                :disabled="!canGenerate"
                @click="handleGenerate"
                style="width: 100%"
              >
                <el-icon v-if="!generating"><VideoPlay /></el-icon>
                {{ generating ? '生成中...' : '生成视频' }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 右侧：任务列表和结果展示 -->
        <div class="result-panel">
          <div v-if="!currentTask && !generating" class="empty-state">
            <el-icon :size="80"><VideoCamera /></el-icon>
            <p>生成的视频将在这里显示</p>
          </div>

          <!-- 任务状态 -->
          <div v-if="currentTask" class="task-status">
            <el-card shadow="hover">
              <template #header>
                <div class="task-header">
                  <span>任务 ID: {{ currentTask.id }}</span>
                  <el-tag :type="getStatusType(currentTask.status)">
                    {{ getStatusText(currentTask.status) }}
                  </el-tag>
                </div>
              </template>

              <div class="task-info">
                <el-descriptions :column="1" border size="small">
                  <el-descriptions-item label="模型">{{ currentTask.model }}</el-descriptions-item>
                  <el-descriptions-item label="分辨率">{{ currentTask.size }}</el-descriptions-item>
                  <el-descriptions-item label="时长">{{ currentTask.seconds }}秒</el-descriptions-item>
                  <el-descriptions-item label="进度">
                    <el-progress :percentage="currentTask.progress || 0" />
                  </el-descriptions-item>
                </el-descriptions>

                <!-- 视频预览 -->
                <div v-if="currentTask.status === 'completed' && currentTask.url" class="video-preview">
                  <video
                    :src="currentTask.url"
                    controls
                    style="width: 100%; max-height: 400px; border-radius: 8px;"
                  />
                  <div class="video-actions">
                    <el-button
                      type="primary"
                      :icon="Download"
                      @click="downloadVideo"
                    >
                      下载视频
                    </el-button>
                    <el-button
                      type="success"
                      :icon="CopyDocument"
                      @click="copyVideoUrl"
                    >
                      复制链接
                    </el-button>
                  </div>
                </div>

                <!-- 错误信息 -->
                <div v-if="currentTask.status === 'failed' && currentTask.error" class="error-info">
                  <el-alert
                    type="error"
                    :title="'生成失败'"
                    :description="JSON.stringify(currentTask.error)"
                    show-icon
                    :closable="false"
                  />
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  VideoPlay,
  VideoCamera,
  Upload,
  Delete,
  Download,
  CopyDocument,
  InfoFilled
} from '@element-plus/icons-vue'
import { videoApi } from '@/services/videoApi'

defineOptions({
  name: 'VideoGeneration'
})

// 表单数据
const form = reactive({
  model: 'sora-2',
  prompt: '',
  seconds: '15',
  size: '1280x720'
})

const generating = ref(false)
const currentTask = ref(null)
const referenceImage = ref(null)
const referenceImageUrl = ref('')
const pollInterval = ref(null)

// 计算属性
const canGenerate = computed(() => {
  return form.prompt.trim().length > 0 && form.model
})

// 处理图片上传
const handleImageChange = (file) => {
  referenceImage.value = file.raw
  const reader = new FileReader()
  reader.onload = (e) => {
    referenceImageUrl.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 移除参考图片
const removeReferenceImage = () => {
  referenceImage.value = null
  referenceImageUrl.value = ''
}

// 生成视频
const handleGenerate = async () => {
  if (!canGenerate.value) {
    ElMessage.warning('请填写视频描述')
    return
  }

  generating.value = true
  currentTask.value = null

  try {
    // 构建FormData
    const formData = new FormData()
    formData.append('prompt', form.prompt)
    formData.append('model', form.model)
    if (form.seconds) {
      formData.append('seconds', form.seconds)
    }
    if (form.size) {
      formData.append('size', form.size)
    }
    if (referenceImage.value) {
      formData.append('input_reference', referenceImage.value)
    }

    const response = await videoApi.generateVideo(formData)

    if (response && response.id) {
      currentTask.value = response
      ElMessage.success('视频生成任务已创建，正在处理...')
      
      // 开始轮询任务状态
      startPolling(response.id)
    } else {
      throw new Error('未返回任务ID')
    }
  } catch (error) {
    console.error('生成视频失败:', error)
    if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
      ElMessage.error('请求超时，请稍后重试')
    } else {
      ElMessage.error('生成失败：' + (error.message || '未知错误'))
    }
  } finally {
    generating.value = false
  }
}

// 开始轮询任务状态
const startPolling = (videoId) => {
  // 清除之前的轮询
  if (pollInterval.value) {
    clearInterval(pollInterval.value)
  }

  // 立即查询一次
  pollTaskStatus(videoId)

  // 每5秒轮询一次
  pollInterval.value = setInterval(() => {
    pollTaskStatus(videoId)
  }, 5000)
}

// 轮询任务状态
const pollTaskStatus = async (videoId) => {
  try {
    const response = await videoApi.getVideoTask(videoId)
    
    if (response) {
      currentTask.value = response
      
      // 如果任务完成或失败，停止轮询
      if (response.status === 'completed' || response.status === 'failed') {
        stopPolling()
        
        if (response.status === 'completed') {
          ElMessage.success('视频生成完成！')
        } else {
          ElMessage.error('视频生成失败')
        }
      }
    }
  } catch (error) {
    console.error('查询任务状态失败:', error)
    // 不显示错误，继续轮询
  }
}

// 停止轮询
const stopPolling = () => {
  if (pollInterval.value) {
    clearInterval(pollInterval.value)
    pollInterval.value = null
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    queued: 'info',
    processing: 'warning',
    completed: 'success',
    failed: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    queued: '排队中',
    processing: '处理中',
    completed: '已完成',
    failed: '失败'
  }
  return statusMap[status] || status
}

// 下载视频
const downloadVideo = async () => {
  if (!currentTask.value || !currentTask.value.id) {
    ElMessage.warning('没有可下载的视频')
    return
  }

  try {
    const blob = await videoApi.getVideoContent(currentTask.value.id)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `video-${currentTask.value.id}-${Date.now()}.mp4`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('视频下载成功')
  } catch (error) {
    console.error('下载视频失败:', error)
    ElMessage.error('下载失败')
  }
}

// 复制视频链接
const copyVideoUrl = async () => {
  if (!currentTask.value || !currentTask.value.url) {
    ElMessage.warning('没有可复制的链接')
    return
  }

  try {
    await navigator.clipboard.writeText(currentTask.value.url)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 组件卸载时清除轮询
onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
.video-generation {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.main-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
  color: #2c3e50;
}

.header-subtitle {
  font-size: 14px;
  color: #909399;
}

.generation-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-top: 20px;
}

.params-panel {
  padding-right: 20px;
  border-right: 1px solid #e4e7ed;
}

.result-panel {
  min-height: 500px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.empty-state p {
  margin-top: 16px;
  font-size: 14px;
}

.task-status {
  margin-top: 20px;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-info {
  margin-top: 16px;
}

.video-preview {
  margin-top: 20px;
}

.video-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  justify-content: center;
}

.error-info {
  margin-top: 16px;
}

.tip-text {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.reference-image-preview {
  margin-top: 12px;
  position: relative;
  display: inline-block;
}

.reference-image-preview img {
  width: 200px;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.reference-image-preview .el-button {
  position: absolute;
  top: 4px;
  right: 4px;
}

@media (max-width: 1024px) {
  .generation-container {
    grid-template-columns: 1fr;
  }

  .params-panel {
    padding-right: 0;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
    padding-bottom: 24px;
    margin-bottom: 24px;
  }
}
</style>

